<template>
  <div>

    <Upload  :action="action" :default-file-list="fileList" :on-preview="onPreview" :on-remove="onRemove"
             :on-error="onError"
             :on-success="fileOnSuccess">
      <Button icon="ios-cloud-upload-outline" v-show="ifEdit">点击上传附件</Button>
    </Upload>

  </div>
</template>

<script>
  import ajax from "../ajax_util"
  export default {
    name: 'file_uploader',
    props:{
      fileList:{
        type:Array,
        default:function () {
          return [ ]
        }
      },
      action:{
        default:"http://localhost:8083/kentry/uploadfile"
      },
      ifEdit:{
        default:false
      }
    },
    data() {
      return {

      }
    },
    methods: {

      fileOnSuccess(response, file, fileList){
        file["url"]=response;
        console.log("new file ",response)
        this.fileList.push(file)
      },
      onError(error, file, fileList){
        this.$Notice.error({
          title: '上传文件失败',
          desc:  '请注意文件名长度以及文件格式是否符合要求，如不能解决请联系管理员进行处理'+this.action
        });
        console.log(error)
      },
      onPreview(file){
        // console.log("onPreview",file.url)
        // console.log(file.response)
        var url=this.CONFIG.url_know+"/files/"+file.url
        window.open(url, '_blank')
      },
      onRemove(file,fileList){
        // if(!this.ifEdit){
        //   this.$Notice.error({
        //     title: '无法操作',
        //     desc:  '请打开编辑模式后再进行该操作！（操作不可逆）'
        //   });
        //   return
        // }
        var that=this;
        var url=this.CONFIG.url_know+"/kentry/file/"+window.btoa(file.url);
        // console.log("准备删除：",url,fileList.length )
        ajax.del({url:url,that:that,success:function(){


            for(var i in that.fileList){//寻找删除的file
              let f_url=that.fileList[i]["url"]
              console.log(f_url,file.url)
              if(f_url==file.url){
                console.log("del",i)
                that.fileList.splice(i,1)
                break;
              }

            }
             // console.log(that.fileList.length,fileList.length)
        }})
        // console.log(file.name,file.url)
      }

    },
    mounted(){
      // console.log("file uploader action:",this.action)
    },
    watch:{
      fileList:function(new_v,old_v){
        // console.log("watch")
       // console.log(this.fileList)// name:文件原名 url：文件在服务器的uuid name
        this.$emit('update:fileList', this.fileList)
      }
    },

  }

</script>

<style>
</style>
